package com.utc.teamcenter.common.util;

import java.awt.Window;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.swing.SwingUtilities;

import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;

import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.services.ISelectionMediatorService;
import com.teamcenter.rac.util.MessageBox;

public class EclipseUtil {

	public static final int ERROR = MessageBox.ERROR;
	public static final int INFOMATION = MessageBox.INFORMATION;
	public static final int WARNING = MessageBox.WARNING;

	private EclipseUtil() {

	}

	public static void invokeLater(Runnable runnable) {
		SwingUtilities.invokeLater(runnable);
	}

	public static MessageBox error(Throwable throwable) {
		StringWriter stringWriter = new StringWriter();
		PrintWriter writer = new PrintWriter(stringWriter);
		throwable.printStackTrace(writer);

		return MessageBox.post(stringWriter.toString(), "Exception",
				MessageBox.ERROR);
	}

	public static MessageBox info(String msg) {
		return MessageBox
				.post(msg, Messages.INFOMATION, MessageBox.INFORMATION);
	}

	public static MessageBox warn(String msg) {
		return MessageBox.post(msg, Messages.WARNING, MessageBox.WARNING);
	}

	public static MessageBox error(String msg) {
		return MessageBox.post(msg, Messages.ERROR, MessageBox.ERROR);
	}

	public static MessageBox showMsg(String title, String msg, int type) {
		return MessageBox.post(msg, title, type);
	}

	public static MessageBox showMsg(Window window, String title, String msg,
			int type) {
		return MessageBox.post(window, msg, title, type);
	}

	public static InterfaceAIFComponent[] getTargetComponents() {
		BundleContext bundleCtx = FrameworkUtil.getBundle(EclipseUtil.class)
				.getBundleContext();
		ISelectionMediatorService selectionSvc = (ISelectionMediatorService) bundleCtx
				.getService(bundleCtx
						.getServiceReference(ISelectionMediatorService.class
								.getName()));
		InterfaceAIFComponent[] pasteTargets = selectionSvc
				.getTargetComponents();

		return pasteTargets;
	}

	public static InterfaceAIFComponent getTargetComponent() {
		InterfaceAIFComponent[] targets = getTargetComponents();
		if (targets != null && targets.length >= 1) {
			return targets[0];
		}

		return null;
	}
}
